/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.chenweihuacwh.service.orderManage;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.javaeye.chenweihuacwh.dao.orderManage.PurchaseOrderDAO;
import com.javaeye.chenweihuacwh.dao.orderManage.ReasonDAO;
import com.javaeye.chenweihuacwh.dto.orderManage.PurchaseOrder;
import com.javaeye.chenweihuacwh.dto.orderManage.Reason;
import com.javaeye.chenweihuacwh.util.DateUtils;
import com.javaeye.chenweihuacwh.web.PageInfo;
import com.javaeye.chenweihuacwh.web.orderManage.OrderCondition;

public class PurchaseOrderService implements IPurchaseOrderService {
	
	private static Log log = LogFactory.getLog(PurchaseOrderService.class);
	
	private PurchaseOrderDAO dao;
	
	private ReasonDAO reasonDao;
	
	public void setDao(PurchaseOrderDAO dao) {
		this.dao = dao;
	}
	
	public void setReasonDao(ReasonDAO reasonDao) {
		this.reasonDao = reasonDao;
	}

	@SuppressWarnings("unchecked")
	public List getPurchaseOrderList(OrderCondition condition, PageInfo pageInfo) {
		List result = dao.getPageData(condition, pageInfo);
		if (result == null || result.size() == 0) {
			log.warn("数据库中未找到指定的订单信息");
		}
		return result;
	}

	public PurchaseOrder getPurchaseOrderInfo(String orderId) {
		PurchaseOrder order = dao.getPurchaseOrderInfo(orderId);
		if (order == null) {
			log.warn("数据库中未找到指定的订单信息，单号：" + orderId);
			return new PurchaseOrder();
		}
		return order;
	}
	
	public void removePurchaseOrder(String orderId) {
		dao.removePurchaseOrder(orderId);
	}
	
	public void savePurchaseOrder(PurchaseOrder order) {
		if (null == order.getId() || "".equals(order.getId())) {
			String orderId = DateUtils.dateToString("yyyyMM");
			int maxId = dao.getMaxPurchaseOrderId(orderId) + 1;
			orderId = orderId + String.format("%02d", maxId);
			log.debug("生成的订单编号：" + orderId);
			//生成出货单ID
			order.setId(orderId);
		}
		order.setStatus(IOrderService.ORDER_STATES_CREATED);
		dao.savePurchaseOrder(order);
		
		double hours = DateUtils.getDateOffsetHour(order.getOrderDate(), DateUtils.now());
		if (hours > Reason.LATER_HOUR) {
			Reason reason = new Reason(
					Reason.REASON_CATEGORY_BUSINESS, 
					order.getId(),
					"登录订单在签订日期" + Reason.LATER_HOUR + "个小时之后");
			reasonDao.saveReason(reason);
		}
	}
}
